package com.myworld.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 对文件进行压缩
 * 可解决zip文件里子文件乱码问题
 * @author 倔小犟
 */
public class ZipUtil {
  

    /** 
     * 功能:压缩多个文件成一个zip文件 
     * @param srcfile：源文件列表 
     * @param zipfile：压缩后的文件 
     * @return true:成功  false：失败
     */  
    public static boolean zipFiles(File[] srcfile,File zipfile){  
        boolean reFlag = false;
        byte[] buf=new byte[10240];  
        ZipOutputStream out = null;
        FileInputStream in = null;
        try {  
            //ZipOutputStream类：完成文件或文件夹的压缩  
            out=new ZipOutputStream(new FileOutputStream(zipfile));  
            //注意此处编码设置
            out.setEncoding("gbk");
            for(int i=0;i<srcfile.length;i++){  
                in=new FileInputStream(srcfile[i]);  
                out.putNextEntry(new ZipEntry(srcfile[i].getName()));  
                int len;  
                while((len=in.read(buf))>0){  
                    out.write(buf,0,len);  
                }  
                out.closeEntry();  
                in.close();  
                in = null;
            }  
            out.close();  
            out = null;
            reFlag = true;
            
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally{
            if(in!=null){
                try {
                    in.close();
                    in = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                    out = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } 
        return reFlag;
    }  
  }
